using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;

namespace SPRepository
{
    public class MultiTaxonomyFieldType : SimpleFieldType<IEnumerable<TaxonomyFieldDto>>
    {
        public MultiTaxonomyFieldType(Guid fieldId) : base(fieldId)
        {
        }

        public override IEnumerable<TaxonomyFieldDto> GetValue(SPListItem item)
        {
            var field = GetField<TaxonomyField>(item);
            TaxonomyFieldValueCollection taxonomyFieldValueCollection = TaxonomyFieldUtilities.GetValues(item, field);
            List<TaxonomyFieldDto> dtoList =
                taxonomyFieldValueCollection.Select(
                    taxValue => new TaxonomyFieldDto(taxValue.Label, new Guid(taxValue.TermGuid))).ToList();
            return dtoList;
        }

        public override void SetValue(SPListItem item, IEnumerable<TaxonomyFieldDto> values)
        {
            var field = GetField<TaxonomyField>(item);
            var termGuids = new List<Guid>();
            if (values != null)
            {
                termGuids.AddRange(values.Select(value => value.TermGuid));
            }
            TaxonomyFieldUtilities.SetValues(item, field, termGuids);
        }
    }
}